package com.szh.easyexcel.service.impl;

import com.alibaba.fastjson.JSON;
import com.szh.easyexcel.mapper.ProductMapper;
import com.szh.easyexcel.model.Product;
import com.szh.easyexcel.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: SongZiHao
 * @date: 2023/5/27
 */
@Service
public class ProductServiceImpl implements ProductService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Autowired
    private ProductMapper productMapper;

    /**
     * Excel上传之后，进行读取，将数据批量插入到数据库中
     * @param productList 商品集合
     * @return 受影响行数
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,
                   isolation = Isolation.REPEATABLE_READ,
                   rollbackFor = Exception.class)
    public int insertBatch(List<Product> productList) {
        LOGGER.info("insertBatch start....");
        LOGGER.info("将Excel中的数据转换之后 ===> {}", JSON.toJSONString(productList));
        int row = productMapper.insertBatch(productList);
        if (row == productList.size()) {
            LOGGER.info("Excel上传成功，数据批量插入成功！！！");
            return row;
        } else {
            LOGGER.error("数据批量插入失败....");
            return 0;
        }
    }
}
